#-*- coding:utf8 -*-
"""
Function attributes:
* load: boolean. Optional. If False the function will not load.
* name: string. Optional.
* priority: string. Optional. Three values are available: "high", "medium" or "low",
  default value: "medium".
* thread: boolean. Optional. If True, function will work by starting a thread.
* rule: string or regexp object. Required.
* aliases: list of string or regexp objects. Optional.
* fullmsg: boolean. Optional. If True, pattern is searched on whole message, else
  pattern is a command, the message must begin with a sign.

* access
* evttypes: must be tuple
* limit
* channels
* url
* showas
"""
from __future__ import division
import difflib, httplib, re, time
from util.functions import *
from core.optimizers import fmt, format_number
from util.xplor import Xplorer
from util.pywikilib import WikiLink, Site, Page, User, Time
from core.ircfuncs import quiet_nick, irc_lower, get_account, get_user
from util.sitematrix import viquimedia
from dateutil.relativedelta import relativedelta as rdelta
field = "wm users"

def clean_ts(string):
	return string.replace("T"," ")[:-4]

get_gender = lambda lang, gender: {
		"ca": {"male":"L'usuari ","female":u"La usuària ", "unknown": ""},
		"en": {"male": "User ", "female": "User ", "unknown": "User "},
		"pt": {"male":"O usuário ","female": u"A usuária ", "unknown": ""},
		"it": {"male":"L'utente ","female": u"L'utente ", "unknown": ""},
		"fr": {"male":"L'utilisateur ","female": u"L'utilisatrice ", "unknown": ""},
		"es": {"male":"El usuario ", "female":u"La usuaria ", "unknown": ""},
	}[lang][gender]

def contribs(bot, evt, cmd):
	""".c [-user ]<user> - Show contributions from a user."""
	if evt.type.startswith("priv"):
		bot.reply(evt, "This command cannot be used in private.")
		return
	nick = get_user(cmd, evt)
	wlink = WikiLink(nick, evt.lang, evt.fam, is_user=True)
	nick = nick.split(":")[-1]
	usr = get_account(bot, nick)
	user = User(wlink.site(), usr)
	unfo = user.info()
	sitename = viquimedia.get(wlink.sitename(), wlink.sitename()) if evt.lang == "ca" else wlink.sitename()
	bot.reply(evt,
		u"%s&B;%s&N; has &t;%s&N; contributions in &l;%s&N;",
		get_gender(evt.lang, unfo['gender']),
		quiet_nick(user.nick(), bot.channels[evt.chan].users()),
		format_number(unfo['editcount'], 0),
		sitename
	)
contribs.rule = "c"

get_symbol = lambda gender: {"male": u" &r;♂&N;","female": u" &p;♀&N;", "unknown": ""}[gender]

def format_reltime(delta):
	rtn=[]
	for x,y  in ((delta.years,"y"), (delta.months,"m"), (delta.days,"d"), (delta.hours,"h"), (delta.minutes,"m"), (delta.seconds,"s")):
		if x>0:
			rtn.append("%s%s" % (x,y))
	return rtn[:3]

import locale
from platform import system
os = "win" if system().lower() == "windows" else "unix"
strings = {
	"ca": {
		"win": "Catalan",
		"unix": "ca_ES",
	},
	"es": {
		"win": "Spanish",
		"unix": "es_ES",
	},
	"en": {
		"win": "English",
		"unix": "en_UK",
	},
	"pt": {
		"win": "Portuguese",
		"unix": "pt_PT",
	},
	"it": {
		"win": "Italian",
		"unix": "it_IT",
	},
}
def set_local(code):
	locale.setlocale(locale.LC_TIME, strings[code][os])

def info(bot, evt, cmd):
	""".info <user>"""
	set_local(evt.lang)
	nick = get_user(cmd, evt)
	wlink = WikiLink(nick, evt.lang, evt.fam, is_user=True)
	nick = nick.split(":")[-1]
	usr = get_account(bot, nick) if not cmd.opts['strict'] else nick
	user = User(wlink.site(), usr)
	unfo = user.about(force_reg = cmd.opts['force'])
	if unfo['extra'] != "missing":
		diff = 0; delta = None
		registred = ""
		if unfo['registration']:
			registred = " | &B;registred:&N; %s" % unfo['registration'].to_short_local_string()
			reg = unfo['registration']
		else:
			if unfo['editcount'] >= 1:
				registred = " | &B;registred:&N; &o;%s&N;" % unfo['first timestamp'].to_short_local_string()
				reg = unfo['first timestamp']
			else:
				registred = " | &B;registred:&N; &r;%s&N;" % Time().to_short_local_string()
				reg = Time()

		#how long is editing
		if unfo['editcount'] > 1:
			delta = rdelta(unfo['last timestamp'](), reg())
			registred += " &+g;[%s active]&N; "	% (" ".join(format_reltime(delta)))
		elif unfo['editcount'] == 1:
			print unfo['first timestamp']()
			delta = rdelta(Time().obj, unfo['first timestamp']())
			registred += " &+g;[%s active]&N; "	% (" ".join(format_reltime(delta)))

		#average eds/day
		if unfo['editcount'] > 1:
			delta = unfo['last timestamp']() - reg()
			if delta.days:
				registred += "(&+g;%.2f&N; eds/day) " % (unfo['editcount']/float(delta.days))
		elif unfo['editcount'] == 1:
			delta = unfo['first timestamp']() - reg()
			if delta.days:
				registred += "(&+g;%.2f&N; eds/day) " % (unfo['editcount']/float(delta.days))

		#contribs
		first = "&B;first&N; %s [[&l;%s&N;]] | " % (
				unfo['first timestamp'].to_short_local_string(),
				unfo['first edit']
			) if unfo['editcount'] >= 1 else ""
		ldiff = "&+g;[%s ago]&N; " % (
			" ".join(format_reltime(rdelta(Time().obj, unfo['last timestamp']()))),
		) if unfo['editcount'] > 1 else ""
		last = "&B;last&N; %s [[&l;%s&N;]] %s| " % (
				unfo['last timestamp'].to_short_local_string(),
				unfo['last edit'],
				ldiff
		) if unfo['editcount'] > 1 else ""

		bot.reply(evt,
			u"%s%s%s| &B;contribs:&N; %s | %s%s&B;groups:&N; %s | http://%s/wiki/Special:Contributions/%s",
			user.nick(), get_symbol(unfo['gender']),
			registred,
			format_number(unfo['editcount'], 0),
			first,
			last,
			unfo['groups'],
			wlink.sitename(), wikiquote(user.nick()),
		)
	else:
		bot.reply(evt, "user does not exist.")
	if unfo.has_key('groups') and unfo['groups'] == "anonymous":
		import geoloc
		cmd.arguments = cmd.arguments.split(":")[-1]
		geoloc.wimip(bot, evt, cmd)
info.rule = "info"
info.aliases = ("wikiacc", "about")
info.url = "http://$sitename/w/api.phpformat=jsonfm&action=query&list=users&usprop=editcount|gender|groups|registration&ususers=$user"

def get_delay_and_site(bot, cmd, evt):
	delay, wiki = "", ""
	if cmd.arguments:
		wiki = re.search("([a-z\-:]+:?)", cmd.arguments) or ""
		if wiki:wiki=wiki.group(1)
		delay = re.search("(\d+)( ?[dhm])?", cmd.arguments, re.I)
		delay = (int(delay.group(1)), delay.group(2) and delay.group(2).lower().strip() or "h") if delay else (24, "h")
		if delay[1] == "d": delay = (delay[0], "D")
		overload=False
		if delay[1] == "D":
			if delay[0] > 2 or delay[0] < 1: overload = True
		elif delay[1] == "h":
			if delay[0] > 48 or delay[0] < 1: overload = True
		elif delay[1] == "m":
			if delay[0] > 60*24*2 or delay[0] < 10: overload = True
		if overload:
			bot.reply(evt, "Time overload. Please choose a lapse between 2 days (2d) and 10 minutes (10m)")
			return True
	site = WikiLink(wiki or "", evt.lang, evt.fam).site()
	if not delay: delay = (24, "h")
	delay_tpl = delay
	delay = Time().subtract(*delay)
	return delay, delay_tpl, site

def recent_changes(site, rcend, rctype, excepts):
	params = {
		"list": "recentchanges",
		"rcprop": ("user", "title", "flags"),
		"rctype": rctype,
		"rcend": Time(rcend).to_api(),
		#"rcshow": (bots, anons),
		"rclimit": "max"
	}
	if rctype == "new": params["rcnamespace"]=0
	rcstart=True;total=0
	print "user:rank | site := %r | delay := %r" % (site.sitename(), Time(rcend).to_simple_string())
	users={}; bots=set();anons=set();registred=set();articles=set();
	while rcstart:
		if isinstance(rcstart, basestring): params['rcstart'] = rcstart
		q = site.get_api(params)
		events = q['query']['recentchanges']
		total+=len(events)
		for event in events:
			if users.has_key(event['user']):
				users[event['user']].append(event['title'])
			else:
				users[event['user']] = [event['title']]
			if event.has_key("bot"):
				bots.add(event['user'])
			elif event.has_key("anon"):
				anons.add(event['user'])
			else:
				registred.add(event['user'])
			articles.add(event['title'])
			rcstart = q['query-continue']['recentchanges']['rcstart'] \
				if q.has_key('query-continue') and q['query-continue'].has_key("recentchanges") \
				and q['query-continue']["recentchanges"].has_key("rcstart") else None
	ranking = {}; total_edits=0
	for user in users:
		ranking[user]=len(users[user])
		total_edits += len(users[user])
	rvs_ranking = {}
	for user in ranking:
		if rvs_ranking.has_key(ranking[user]): rvs_ranking[ranking[user]].append(user)
		else: rvs_ranking[ranking[user]]=[user]
	rank=[]; length=0
	for edits in reversed(sorted(rvs_ranking.keys())):
		usr=rvs_ranking[edits]
		if excepts['nobots']:
			usr = [u for u in usr if u not in bots]
		if excepts['noanons']:
			usr = [u for u in usr if u not in anons]
		length += len(usr)
		rest = length - 10
		if rest>0:
			usr = usr[:-rest]
		if not usr: continue
		rank.append(", ".join([u"&%s;%s&N; (&t;%i&N;)" % ("l" if user in registred else "+g" if user in bots else "+e", user, edits) for user in usr]))
		if length > 10: break
	print len(registred), len(bots), len(anons)
	return total_edits, users, articles, rank

def editor_ranking(bot, evt, cmd):
	""".rank <site> <time> [-nobots] [-noanons] &B;-&N; It returns the ranking about last editors on a <site> since last <time>. """ \
	"""<time> is a value between 2 days and 10 minutes, where 'd' is for days, 'h' for hours and 'm' for minutes."""
	excepts = {"nobots": cmd.opts['nobots'], "noanons": cmd.opts['noanons']}
	delay, delay_tpl, site = get_delay_and_site(bot, cmd, evt)
	total_edits, users, articles, ranking = recent_changes(site, delay, ("new","edit"), excepts)
	units={
		"D": "days",
		"h": "hours",
		"m": "minutes"
	}
	bot.reply(evt,
		"ranking for last %i %s on &B;%s&N;: %s • &B;total edits:&N; %i • "
		"total of &B;users:&N; %i (%.2f eds/user) &B;diff articles:&N; %i  (%.2f eds/article)",
		delay_tpl[0],
		units[delay_tpl[1]],
		site.abredged_sitename(),
		", ".join(ranking),
		total_edits,
		len(users),
		float(total_edits)/len(users),
		len(list(articles)),
		float(total_edits)/len(list(articles))
	)
editor_ranking.rule = "rank"
editor_ranking.thread = True

def creator_ranking(bot, evt, cmd):
	""".creators <site> <time> [-nobots] [-noanons] &B;-&N; It returns the ranking about last editors on a <site> since last <time>. """ \
	"""<time> is a value between 2 days and 10 minutes, where 'd' is for days, 'h' for hours and 'm' for minutes."""
	delay, delay_tpl, site = get_delay_and_site(bot, cmd, evt)
	excepts = {"nobots": cmd.opts['nobots'], "noanons": cmd.opts['noanons']}
	total_edits, users, articles, ranking = recent_changes(site, delay, "new", excepts)
	units={
		"D": "days",
		"h": "hours",
		"m": "minutes"
	}
	bot.reply(evt,
		u"ranking for last %i %s on &B;%s&N;: %s • total of &B;created articles:&N; %i • total of &B;users:&N; %i (%.2f arts/user)",
		delay_tpl[0],
		units[delay_tpl[1]],
		site.abredged_sitename(),
		", ".join(ranking),
		total_edits,
		len(users),
		float(total_edits)/len(users),
	)
creator_ranking.rule = "creators"
creator_ranking.aliases = ["botopedia"]
creator_ranking.thread = True

def stat(bot, evt, cmd):
	#estat de l'usuari a la Viquipèdia
	if re.search(r"^cur(?:stat)?$", cmd):
		usuari=nomVP(requestedUser)
		estat=getURL("http://%s.%s.org/wiki/Usuari:%s/Estat"%(LANG,FAM,urlWiki(usuari))).split('<!-- start content -->')[1].split('<!-- end content -->')[0].decode('utf-8','replace')
		if 'id="noarticletext"' not in estat:
			try:
				estat=estat.split('<p>')[1].split('</p>')[0]
				if not estat in [u'en línia','desconnectat', 'connectat', 'ocupat', 'inactiu','Funcionant','Aturat']:
					estat="desconegut"
			except:
				estat="desconegut"
			if estat in [u"en línia","connectat","Funcionant"]:
				estat=BOLD+GREEN+estat+NORMAL
			elif estat=="ocupat":
				estat=BOLD+OLIVE+estat+NORMAL
			elif estat in ["desconnectat", "Aturat"]:
				estat=BOLD+RED+estat+NORMAL
			else:
				estat=BOLD+DARK_GRAY+estat+NORMAL
			estat2, darreraEdicio =estatVP(usuari,LANG,FAM)
			msg=u"L'estat de l'usuari %s en la Viquipèdia és: %s. Darrera edició %s" % (quietNick(usuari,bot.connected), estat,\
				  time.strftime("%H:%M (%d-%m-%y)",time.localtime(darreraEdicio)))
			bot.pubmsg(msg.encode('utf-8'))
		else:
			estat, darreraEdicio =estatVP(usuari,LANG,FAM)
			if estat ==0:
				estat=BOLD+GREEN+"connectat"+NORMAL
			elif estat==1:
				estat=BOLD+OLIVE+"absent"+NORMAL
			else:
				estat=BOLD+DARK_GRAY+"desconegut"+NORMAL
			if darreraEdicio:
				estat=estat+u". Darrera edició "+time.strftime("%H:%M (%d-%m-%y)",time.localtime(darreraEdicio))
			msg=u"L'estat de l'usuari %s en la Viquipèdia és: %s"%(quietNick(usuari,bot.connected),estat)
			bot.pubmsg(msg.encode('utf-8'))
			#bot.pubmsg(u"Usuari sense pàgina d'estat o inexistent.".encode('utf-8'))

def usrstatus(bot, evt, cmd):
	user, site= net.whowhere(nick,args)
	user=nomVP(user)
	lang=site.split(".")[0]
	proj=site.split(".")[1]
	contribs=net.pageText("http://%s/w/api.php?action=query&list=users&ususers=%s&usprop=editcount"%(site,trurl(user)))
	contribs=re.search('<span style="color:blue;">&lt;user name=&quot;(.*?)&quot; editcount=&quot;(\d+)&quot; /&gt;</span>',contribs)
	if contribs:
		contribs=u" Té $t%s$N contribucions." % contribs.group(2)
	else:
		contribs=""

	url = "http://%s/w/api.php?action=query&list=usercontribs&ucuser=%s&uclimit=1&format=xmlfm" %(site,trurl(user))
	apidata=net.pageText(url)
	lastedit=re.search(r'<span style="color:blue;">&lt;item user=&quot;.*?&quot; pageid=&quot;.*?&quot; revid=&quot;.*?&quot; ns=&quot;\d+?&quot; title=&quot;(?P<title>.*?)&quot; timestamp=&quot;(?P<ts>.*?)&quot; (?:minor=&quot;&quot; )?(?:top=&quot;&quot; )?(?:comment=&quot;.*?&quot; )?/&gt;</span>',apidata)
	if lastedit:
		lastedit=lastedit.group('ts')
		lastedit=apiTime(lastedit)[0]
	if not lastedit:
		msg=u"L'estat de l'usuari $l%s$N en $E$l%s$N es: $E$gdesconegut$N. Potser no existeix est usuari, que el seu nom sia incorrecte o que el servidor no responga." % (user, site)
		msg = colors(msg)
		c.privmsg(canal,msg.encode('utf-8'))
	elif time.time() - lastedit <= 1800:
		status="$vconnectat$N"
	elif (time.time())-lastedit>1800:
		status="$rdesconnectat$N"
	if lastedit:
		usrList = self.channels[canal].users() if canal in self.channels.keys() else []
		lastedit=time.strftime("%H:%M %d-%m-%y",time.localtime(lastedit))
		msg=u"L'estat de l'usuari $b%s$N en $E$b%s$N és: %s. Darrera edició: $b%s$N.%s" % (quietNick(user,usrList), site, status, lastedit, contribs)
		msg = colors(msg)
		c.privmsg(canal,msg.encode('utf-8'))
usrstatus.rule = ["ustat"]

def blocks(bot, evt, cmd):
	if not cmd.arguments:
		bot.reply(evt, "user was expected")
		return True
	params = {
		"action": "query",
		"list": "blocks",
	}
	target = cmd.arguments or ""

	is_user = not target.split(":")[-1].startswith("#")
	wl = WikiLink(target, evt.lang, evt.fam, is_user)
	target = target.split(":")[-1]
	if target.startswith("#"):
		params['bkids'] = target.split("|")[0][1:].strip()
	else:
		params['bkusers'] = quote(target.strip())
	print "wikiusers.py blocks()", target
	data = wl.site().get_api(params)
	if data.has_key("query"):
		data = data['query']
		if data['blocks']:
			block = data['blocks'][0]
			print block
			id = block['id']
			by = block['by']
			user = block['user']
			since = Time(block['timestamp']).to_abredged_string()
			till = Time(block['expiry']).to_abredged_string() if block['expiry'] != "infinity" else block['expiry']
			opts=[]
			allowusertalk = opts.append("allow user talk") if block.has_key('allowusertalk') else ""
			autoblock = opts.append("autoblock") if block.has_key('autoblock') else ""
			nocreate = opts.append("no create") if block.has_key('nocreate') else ""
			noemail = opts.append("no email") if block.has_key('noemail') else ""
			anononly = opts.append("anonimous only") if block.has_key('anononly') else ""
			opts = ", ".join(opts)
			reason = block['reason']
			bot.reply(evt,
				"[#%s] &B;&U;&+e;%s&N; &B;blocked&N; &l;%s&N; &B;on&N; %s &B;till&N; %s. &B;Options:&N; %s. &B;Reason:&N; %s",
				id, by, user, since, till, opts, reason
			)
		else:
			bot.reply(evt, "User has no block.")
	else:
		bot.reply(evt, "No such block.")
	return
blocks.rule=["blocks","bl"]
blocks.url = "http://$proj/w/api.php?format=jsonfm&action=query&list=blocks"

def globalblock(bot, evt, cmd):
	""".gblock <ip> - Check if <ip> is blocked globally on meta."""
	if not cmd.arguments:
		bot.reply(evt, "user was expected")
		return True
	wl = WikiLink(args, "meta")
	user=wl.title()
	params = {
		"blockinfo": {
			"action": "query",
			"list": "allusers",
			"aufrom": user,
			"aulimit": 1,
			"auprop": "blockinfo",
		},
		"globalblocks": {
			"action": "query",
			"list": "globalblocks",
			"bgip": user,
			"bgprop": ("id", "address", "by", "timestamp", "expiry", "reason", "range")
		}
	}
globalblock.rule = ['globalblocks','gblock','gbl']
globalblock.thread = True
globalblock.url = "http://meta.wikimedia.org/w/api.php?action=query&list=globalblocks&bgip=%s"

def luxo(bot, irc, cur):
	"""
	<div class="mw-contributions-footer">
	<hr />
	<small>721 projectes analitzats. Hi ha 281 contribucions en 6 projectes.<br></small>
	&blocks=true&lang=ca&showclosed=false&recentonly=false&fullblocklog=true
	"""
	user = encode(cur.args)
	params = {
		"blocks": "true",
		"showclosed": "false",
		"recentonly": "false",
		"fullblocklog": "false",
		"lang": "en",
		"user": user
	}
	url = luxo.url % quote(user)
	bot.reply(evt, url)
	data = Browser.get_query(url, params)
	conclusion = re.search("<small>(?P<sc>\d+) projects scanned. (?P<ct>\d+) contributions found in (?P<pr>\d+) projects.<br></small>",data)
	if conclusion:
		conclusion = bot.translate("Projects scanned: %s, %s contributions in %s projects. ") % (conclusion.group('sc'), conclusion.group('ct'), conclusion.group('pr'))
	else: conclusion = ""
	blocks = re.finditer(
		'<div style=\'border-style:outset;border-color:red;border-width:thick;background-color:#FFDFDC;\'>'
		'<h4>Blocks</h4><ul><li>(?P<ts>\d{4}-\d\d-\d\dT(?:\d\d:){3}) '
		'<a href="http://(?P<proj>.+?)\.org/w/index\.php\?title=User:[^"]+">'
		'(?P<admin>[^<^]+)</a> .+?'
		'expiry time: (?P<expire>[^(]+?)\(.+?\)</li></ul></div>',
		data
	)
	expire_blocks = []
	for block in blocks:
		#print block.groups()
		expire_blocks.append([block.group('proj'),block.group('expire')])
	str_blocks = ", ".join(["on %s for: %s" %( x[0], x[1]) for x in expire_blocks])
	b = bot.translate("Blocks: %i. ") % (len(expire_blocks)) if expire_blocks else bot.translate("No blocks found. ")
	blocks = "%sBlocked %s" % (b, str_blocks) if expire_blocks else ""
	bot.reply(evt, "%s%s", conclusion, blocks)
luxo.rule = 'luxo'
luxo.url = 'http://toolserver.org/~luxo/contributions/contributions.php?user=%s'

def sul(bot, evt, cmd):
	user = get_user(cmd, evt)
	url = sul.url % quote(user)
	ua = {"user-agent": "Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20120405 Firefox/14.0a1"}
	info, html = Xplorer.get_request(url, ua, 120)
	if html:
		dict1={}
		table = lambda x: re.search('SUL info</legend>(.+)<p><strong>Useful links ', x, re.S | re.M)
		items = lambda x: re.findall( r'<p><strong>(.+?) : </strong> (.+?)</p>', x, re.M )
		if table(html):
			for key, value in items(table(html).group(1)):
				dict1.update({key: value})

		dict2 = {}
		table = re.search('List of local accounts</legend>\s+<table class="wikitable sortable">(.+?)</table>', html, re.S | re.M)
		if table:
			keys = re.findall( r'<th>(.+?)</th>', table.group(1), re.S)
			data = re.search( r"</th>\s+</tr>(.+)", table.group(1), re.S | re.M)
			data = re.split(r"</tr>\s+<tr>", data.group(1), 0, re.S | re.M)
			for items in data:
				values = re.findall( r'<td[^>]*>(.*?)</td>', items, re.S | re.M)
				temp = dict(zip(keys, values))
				del temp['Links']
				dict2.update({temp.pop('Local wiki'): temp})

		dict3 = {}
		table = re.search('List of unattached accounts</legend>\s+<table class="wikitable sortable">(.+)</table>', html, re.S | re.M)
		if table:
			keys = re.findall( r'<th>(.+?)</th>', table.group(1), re.S)
			data = re.search( r"</th>\s+</tr>(.+)</tr>", table.group(1), re.S | re.M)
			data = re.split(r"</tr>\s+<tr>", data.group(1), 0, re.S | re.M)
			for items in data:
				values = re.findall( r'<td[^>]*>(.*?)</td>', items, re.S | re.M)
				temp = dict(zip(keys, values))
				del temp['Links']
				dict3.update({temp.pop('Local wiki'): temp})
		data = {}
		data.update(dict1)
		data.update(dict2)
		data.update(dict3)
		accounts = len(dict2)
		unatt = len(dict3); unatt_edits = 0
		edits = 0; noeditwikis = 0
		blocked=[]; unatt_blocked = []
		for acc in dict2:
			edits += int(dict2[acc]['Edit count'])
			if int(dict2[acc]['Edit count'])==0: noeditwikis +=1
			if dict2[acc]['Blocked'] !='no': blocked.append(acc)
		for acc in dict3:
			unatt_edits += int(dict3[acc]['Edit count'])
			if int(dict3[acc]['Edit count'])==0: noeditwikis +=1
			if dict3[acc]['Blocked'] != 'no': unatt_blocked.append(acc)
		nocontribs=" &t;%i&N; projects without edits" % noeditwikis
		total_editcount = "total editcount: &+e;%s&N;." % dict1['Total editcount'] if dict1.get("Total editcount", 0) else ""
		total_unatt_editcount = "total editcount from unattatched projects: &+e;%s&N;." % unatt_edits if unatt_edits else ""
		noSUL = ". SUL account doesn't exist" if re.search("<p>There is no SUL account matching the name ", html) else ""
		blocked=". &r;Blocked&N; on &t;%i&N; wikis: %s" % (len(blocked),", ".join(blocked)) if blocked else ""
		unatt_blocked=". &r;Blocked&N; on &t;%i&N; unattached wikis: %s" % (len(unatt_blocked),", ".join(unatt_blocked)) if unatt_blocked else ""
		total_accounts = accounts + unatt
		statusSummary = " (&p;%i unified&N; accounts and &r;%i unattached&N;). " % (
			accounts, unatt
		)
		bot.reply(evt, "&B;%i accounts&N; matched%s%s%s%s%s%s. %s", total_accounts, statusSummary, total_editcount, total_unatt_editcount, nocontribs, blocked, unatt_blocked, url)
	else: bot.reply(evt, "no txt match")
sul.rule="sul"
#sul.url = "http://toolserver.org/~vvv/sulutil.php?user="
#sul.url = "http://toolserver.org/~quentinv57/tools/sulinfo.php?username=%s&showblocks=1"
sul.url = "http://toolserver.org/~quentinv57/sulinfo/%s?showblocks=1"
sul.thread = True

def central(bot, evt, cmd):
	#http://meta.wikimedia.org/wiki/Special:CentralAuth/$user
	params = {
		"meta": "globaluserinfo",
		"guiuser": cmd.arguments,
		"guiprop": ("groups", "rights", "merged", "unattached")
	}
central.url ="http://meta.wikimedia.org/wiki/Special:CentralAuth/%s"

def created_arts(bot, evt, cmd):
	""".created <user> [-all]"""
	#http://toolserver.org/~tparis/pages/index.php?name=Coet&lang=ca&wiki=wikipedia&namespace=0&redirects=noredirects
	user = evt.source if not isinstance(cmd.arguments, basestring) else cmd.arguments.replace("::","")
	wiki = WikiLink(user, evt.lang, evt.fam, True)
	user, sitename = wiki.title(), wiki.sitename()
	url = fmt(created_arts.url, user, wiki.language(), wiki.family(), "&getall=1" if cmd.opts['all'] else "")
	timeout = int(cmd.opts["timeout"])*60 if cmd.opts["timeout"] and cmd.opts["timeout"].isdigit() else 120
	ua = {"user-agent": "Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20120405 Firefox/14.0a1"}
	info, html = Xplorer.get_request(url, ua, timeout)
	if html:
		table = re.search('(?sm)<h2 class="table">Top Namespace Edits</h2><h2>Pages created by .+?:</h2>(.+)</ol>', html).group(1)
		pages = re.findall(u'(?sm)<li><a href="http://[^.]+\.wikipedia\.org/wiki/[^"]+">(.+?)</a></li>', table)
		bot.reply(evt, "$1 has created $2 pages on $3. $4", user, len(pages), sitename, url)
created_arts.rule = "created"
created_arts.url = "http://toolserver.org/~tparis/pages/index.php?name=$1&lang=$2&wiki=$3&namespace=0&redirects=noredirects$4"
created_arts.thread = True

def editors(bot, evt, cmd):
	"""".editors <site> <timestamp1> <timestamp2>" Returns number of unique editors of a day"""
	if self.cCC(canal, True, nick, "edtors", 3): return
	params = GetParams(args)
	#if not params['api'] and params.arguments(): api=params['api']
	items = do_editor_sql(params['api'])
	bot.pubmsg("edicions: %s || editors: %s%s || http://toolserver.org/~pasqual%s" % (items[0], items[1], items[2], items[3]))
editors.rule = "editors"

def close_matches(options, site):
	next = True
	allusers = {}
	allusers_list = []
	withedonly=True
	target = options['target'].split(":")[-1]
	prefix = options['prefix']
	while next:
		params = {
			"action": "query",
			"list": "allusers",
			"auprefix": target[0].upper(),
			"aulimit": "max"
		}
		if isinstance(next, basestring):
			params['aufrom']=next
		if withedonly:	params["auwitheditonly"] = ""
		data = site.get_api(params)
		for user in data['query']['allusers']:
			allusers[user['name'].lower()] = user['name']
			allusers_list.append(user['name'])
		#print len(allusers)
		next = data['query-continue']['allusers']['aufrom'] if data.has_key("query-continue") else None
	result = difflib.get_close_matches(target.lower(), sorted(allusers.keys()), n=10)
	match = None
	if not options['all']:
		for user in result:
			ic = re.search(target, user, re.I)
			if ic and len(user) == len(target):
				match = allusers[user]
				break
	return match, [allusers[u] for u in result]

def likeness(bot, evt, cmd):
	""".like [-target] <user> [-all]"""
	if not cmd.opts['target']: cmd.opts['target'] = cmd.arguments
	site = WikiLink(cmd.opts['target'], evt.lang, evt.fam).site()
	match, users = close_matches(cmd.opts, site)
	args =[]
	if not match:
		msg = u"no match found, try with: %s %s"
		args.append(", ".join(users))
		args.append(Page(site, fmt("Special:Prefixindex/$target", target = cmd.opts['target'].split(":")[-1])).to_url())
	else:
		msg = u"it seems user is %s %s"
		args.append(match)
		args.append(Page(site, u"Special:Contributions/%s" % match).to_url())

	bot.reply(evt, msg, *args)
likeness.rule = "like"
likeness.chanlang = {"ca": ["paregut", "semblant"]}
likeness.thread = True

def bots(bot, evt, cmd):
	if cmd.arguments: pref = cmd.arguments
	bots = ("BotReversor", "BotPatrulla", "AvisaBot", "SignaBot", "TronaBot")
	params = {
		"list": "users",
		"ususers": bots,
		"usprop": ("editcount","gender")
	}
	wlink = WikiLink(cmd.arguments or "", evt.lang, evt.fam)
	q = wlink.site().get_api(params)
	c = 0; botlist = []
	for user in q['query']['users']:
		botlist.append("&B;%s:&N; &t;%s&N;" % (user['name'], format_number(user['editcount'], 0)))
		c += user['editcount']
	bot.reply(evt, "%s || &B;&U;Total edits:&N; &t;%s&N;", " | ".join(botlist), format_number(c, 0))
bots.rule = "bots"
